/**
 * 
 */
package manet.comm;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;

/**
 * This class provides a threaded unicast listener for receiving messages.
 * @author grin0077
 *
 */
public class UnicastIPListener extends Thread {
	
	private UnicastIPCommunicator comm;
	private InetSocketAddress address = null;
	private int timeout;
	
	public UnicastIPListener(InetSocketAddress addr, UnicastIPCommunicator uComm) {
		super.setDaemon(true);
		
		this.comm = uComm;
		this.address = addr;
		this.timeout = 1000;
	}
	
	public void run() {
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(this.address.getPort());
			socket.setSoTimeout(this.timeout);	
			
			DatagramPacket packet;
			while(this.comm.isListening()) {
				byte[] buffer = new byte[UnicastIPCommunicator.MAX_BYTES];
				packet = new DatagramPacket(buffer, buffer.length);
				try {
					socket.receive(packet);
				
					if(!packet.getAddress().equals(this.address.getAddress())) {
						this.comm.queueMessage(new String(packet.getData()).split("\u0000")[0]);
					}
				} catch (SocketTimeoutException e) {
					// eat it, allow loop to check listening condition
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(socket != null) {
				socket.close();
				socket = null;
			}
		}
	}
}
